package com.example.springbootjackson.requestContext;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 */
@Component
@Slf4j
public class RequestContextInterceptor extends HandlerInterceptorAdapter {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle threadName={}", Thread.currentThread().getName());
        String userId = request.getHeader(RequestContext.USER_ID);
        if (!StringUtils.isEmpty(userId)) {
            try {
                RequestContext.setUserId(Integer.valueOf(userId));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion threadName={}", Thread.currentThread().getName());
        RequestContext.remove();
    }
}
